package com.jz.community.moduleshoppingguide.home.ui.fragment;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpFragment;
import com.jz.community.basecomm.bean.RegionsBean;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.BaseUserUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.basecomm.utils.rxbus.eventType.ToLoginEvent;
import com.jz.community.commview.view.CustomLoadMoreView;
import com.jz.community.commview.view.MyStateView;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.home.bean.ChunnelNewbornBean;
import com.jz.community.moduleshoppingguide.home.bean.HomeFindBean;
import com.jz.community.moduleshoppingguide.home.bean.HomeRecommendBean;
import com.jz.community.moduleshoppingguide.home.bean.LimitGoodsBean;
import com.jz.community.moduleshoppingguide.home.presenter.HomeFindPresenter;
import com.jz.community.moduleshoppingguide.home.ui.HomeFindView;
import com.jz.community.moduleshoppingguide.home.ui.adapter.HomeFindAdapter;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;

public class HomeFindFragment extends BaseMvpFragment<HomeFindView.View, HomeFindPresenter> implements HomeFindView.View, OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R2.id.rv_home_find)
    RecyclerView rvHomeFind;
    @BindView(R2.id.home_find_layout)
    RelativeLayout homeFindLayout;
    @BindView(R2.id.home_main_refresh)
    SmartRefreshLayout homeMainRefresh;
    MyStateView myStateView;
    private View noDataView;
    private View errorView;

    private HomeFindAdapter adapter;
    private int homeRecommendPage = 0;
    private int pageSize = 10;
    private String cityCode;
    private Observable<ToLoginEvent> toLoginRxBusObser;
    private int mDistance;
    private HomeStyleCallback homeStyleCallback;
    private Bitmap mBitmap;
    private RegionsBean.EmbeddedBean.ContentBean region;

    public void setHomeStyleCallback(HomeStyleCallback homeStyleCallback) {
        this.homeStyleCallback = homeStyleCallback;
    }

    public interface HomeStyleCallback {
        void updateHomeStyle(int index, int alpha, int distance);

        void updateHomeToolbarStyle(Palette.Swatch vibrant, View homeBannerView, boolean isBannerData);
    }

    public static HomeFindFragment newInstance() {
        HomeFindFragment fragment = new HomeFindFragment();
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.module_shoppingguide_fragment_home_find;
    }

    @Override
    protected HomeFindPresenter createPresenter() {
        return new HomeFindPresenter(this);
    }


    @Override
    protected void initView() {
        registerLoginByRxBus();
        myStateView = new MyStateView();
        noDataView = myStateView.getNoDataView(getActivity(), (ViewGroup) rvHomeFind.getParent(), "暂无商品！", null);

        errorView = myStateView.getErrorView(getActivity(), (ViewGroup) rvHomeFind.getParent(), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Fragment> list = HomeFindFragment.this.getFragmentManager().getFragments();
                for (Fragment fragment : list) {
                    if (fragment instanceof HomeFragment) {
                        ((HomeFragment) fragment).getHomeData();
                    }
                    break;
                }
            }
        });
        homeMainRefresh.setEnableLoadMore(false);
        homeMainRefresh.setOnRefreshListener(this);
        //设置 RecycleView的显示方式
        LinearLayoutManager llm = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        rvHomeFind.setLayoutManager(llm);
        adapter = new HomeFindAdapter(new ArrayList<>(), getActivity());
        adapter.setGuidePageChangeListener(new HomeFindAdapter.GuidePageChangeListener() {
            @Override
            public void pageChangeListener(Bitmap bitmap, Palette.Swatch vibrant, View homeBannerView, boolean isBannerData) {
                if (isBannerData) {
                    mBitmap = bitmap;
                    if (!Preconditions.isNullOrEmpty(vibrant)) {
                        if (homeStyleCallback != null) {
                            homeStyleCallback.updateHomeToolbarStyle(vibrant, homeBannerView, isBannerData);
                        }
                    }
                } else {
                    if (homeStyleCallback != null) {
                        homeStyleCallback.updateHomeToolbarStyle(null, null, isBannerData);
                    }
                }
            }
        });
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setOnLoadMoreListener(this, rvHomeFind);
        rvHomeFind.setAdapter(adapter);
        rvHomeFind.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mDistance += dy;

                if (Preconditions.isNullOrEmpty(mBitmap)) {
                    return;
                }

                int height = (mBitmap.getHeight() - SHelper.dp2px(getActivity(), 60));
                Logger.e("onGlobalLayout mBitmapHeight=" + mBitmap.getHeight());
                Logger.e("onGlobalLayout height=" + height);
                float percent = (float) mDistance / height;

                int maxAlpha = (int) (percent * 255);

                Logger.e("onGlobalLayout percent=" + percent);
                Logger.e("onGlobalLayout mDistance=" + mDistance);
                if (mDistance <= 0) {
                    homeStyleCallback.updateHomeStyle(0, maxAlpha, mDistance);
                } else if (mDistance > 0 && mDistance < height) {
                    homeStyleCallback.updateHomeStyle(1, maxAlpha, mDistance);
                } else {
                    homeStyleCallback.updateHomeStyle(2, maxAlpha, mDistance);
                }
            }
        });
    }

    @Override
    protected void initLazy(@Nullable Bundle savedInstanceState) {
        super.initLazy(savedInstanceState);
        region = BaseSpUtils.getInstance().getRegion(getActivity());
        if (region != null) {
            cityCode = region.getId() + "";
            mPresenter.getChunnelHomePage(0, 20, region.getId() + "");
        }
    }


    /**
     * 登录处理
     */
    @SuppressLint("CheckResult")
    private void registerLoginByRxBus() {
        toLoginRxBusObser = RxBus.getInstance().register(ToLoginEvent.toLoginRxBusTag, ToLoginEvent.class);
        toLoginRxBusObser.subscribe(toLoginEvent -> {
            if (toLoginEvent.isToPwdLogin() || toLoginEvent.isToWeChatLogin()) {
                RegionsBean.EmbeddedBean.ContentBean region = BaseSpUtils.getInstance().getRegion(getActivity());
                if (region != null) {
                    cityCode = region.getId() + "";
                    mPresenter.getChunnelHomePage(0, 20, region.getId() + "");
                }
            }
        }, throwable -> {
        });
    }

    @Override
    public void showHomeChannel(HomeFindBean homeFindBean) {
        homeMainRefresh.finishRefresh();
        if (homeFindBean.get_embedded().getContent() != null && homeFindBean.get_embedded().getContent().size() > 0) {
            if (!BaseUserUtils.getIsLogin(getActivity())) {
                for (int i = 0; i < homeFindBean.get_embedded().getContent().size(); i++) {
                    if (homeFindBean.get_embedded().getContent().get(i).getType() == HomeFindBean.EmbeddedBean.ContentBean.CHUNNEL_BANNERS_VIEW) {
                        Iterator<HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean> it = homeFindBean.get_embedded().getContent().get(i).getChunnelHomePage().iterator();
                        while (it.hasNext()) {
                            HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean x = it.next();
                            if (x.isLogin().equals("0")) {
                                it.remove();
                            }
                        }
                        break;
                    }
                }
            }
            adapter.refreshAllData(homeFindBean.get_embedded().getContent());
            //获取人气推荐数据
            homeRecommendPage = 0;
            mPresenter.getHomeRecommend(homeRecommendPage, pageSize, AppConstants.ONREFRESH);
        } else {
            adapter.setEmptyView(noDataView);
        }
    }

    @Override
    public void showHomeRecommend(HomeRecommendBean homeRecommendBean, int refreshFlag) {
        if (homeRecommendBean.get_embedded().getContent() != null && homeRecommendBean.get_embedded().getContent().size() > 0) {
            if (refreshFlag == AppConstants.ONREFRESH) {
                HomeFindBean.EmbeddedBean.ContentBean contentBean = new HomeFindBean.EmbeddedBean.ContentBean();
                contentBean.setId(8 + "");
                contentBean.setType(8);
                contentBean.setChunnelHomePage(getRecommendsData(homeRecommendBean));
                adapter.addData(contentBean);
                adapter.loadMoreComplete();
            } else if (refreshFlag == AppConstants.ONLOADMORE) {
                adapter.addRecommendsData(getRecommendsData(homeRecommendBean));
                adapter.loadMoreComplete();
            }
        } else {
            adapter.loadMoreEnd();
        }
        //获取新人专区数据
        mPresenter.getChunnelNewborn(0, 3);
        //获取限时购
        mPresenter.initGoodsData(cityCode, "", "", 0, 10);
    }

    /**
     * 封装人气推荐数据
     *
     * @param homeRecommendBean
     * @return
     */
    private List<HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean> getRecommendsData(HomeRecommendBean homeRecommendBean) {
        List<HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean> list = new ArrayList<>();
        if (homeRecommendBean.get_embedded().getContent().size() > 0) {
            for (int i = 0; i < homeRecommendBean.get_embedded().getContent().size(); i++) {
                HomeRecommendBean.EmbeddedBean.ContentBean contentBean1 = homeRecommendBean.get_embedded().getContent().get(i);
                HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean chunnelHomePageBean = new HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean();
                chunnelHomePageBean.setId(contentBean1.getId());
                chunnelHomePageBean.setTitle(contentBean1.getTitle());
                chunnelHomePageBean.setSellingDesc(contentBean1.getSellingDesc());
                chunnelHomePageBean.setImage(contentBean1.getImages());
                chunnelHomePageBean.setSpStr(contentBean1.getSpStr());
                chunnelHomePageBean.setPrice(contentBean1.getPrice());
                chunnelHomePageBean.setDiscountPrice(contentBean1.getDiscountPrice());
                HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean.LinksBean linksBean = new HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean.LinksBean();
                HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean.LinksBean.GoodsInfoBean goodsInfoBean = new HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean.LinksBean.GoodsInfoBean();
                goodsInfoBean.setHref(contentBean1.getLinks().getGoodsInfo().getHref());
                linksBean.setGoodsInfo(goodsInfoBean);
                chunnelHomePageBean.setLinks(linksBean);
                list.add(chunnelHomePageBean);
            }
        }
        return list;
    }

    public void getChunnelHomePageData() {
        region = BaseSpUtils.getInstance().getRegion(getActivity());
        mPresenter.getChunnelHomePage(0, 20, region.getId() + "");
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        mPresenter.getChunnelHomePage(0, 20, region.getId() + "");
    }

    @Override
    public void onLoadMoreRequested() {
        homeRecommendPage++;
        mPresenter.getHomeRecommend(homeRecommendPage, pageSize, AppConstants.ONLOADMORE);
    }


    @Override
    public void showChunnelNewborn(ChunnelNewbornBean chunnelNewbornBean) {
        if (!Preconditions.isNullOrEmpty(chunnelNewbornBean.get_embedded()) && !Preconditions.isNullOrEmpty(chunnelNewbornBean.get_embedded().getContent())) {
            HomeFindBean.EmbeddedBean.ContentBean contentBean = new HomeFindBean.EmbeddedBean.ContentBean();
            contentBean.setId(9 + "");
            contentBean.setType(9);
            contentBean.setChunnelHomePage(getNewbornData(chunnelNewbornBean));

            if (Preconditions.isNullOrEmpty(adapter.getData())) {
                return;
            }

            if (adapter.getData().size() > 5) {
                adapter.addData(5, contentBean);
            } else {
                adapter.addData(contentBean);
            }
        }
    }

    /**
     * 封装新人专区数据
     *
     * @param chunnelNewbornBean
     * @return
     */
    private List<HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean> getNewbornData(ChunnelNewbornBean chunnelNewbornBean) {
        List<HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean> list = new ArrayList<>();
        for (int i = 0; i < chunnelNewbornBean.get_embedded().getContent().size(); i++) {
            ChunnelNewbornBean.EmbeddedBean.ContentBean contentBean = chunnelNewbornBean.get_embedded().getContent().get(i);
            HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean chunnelHomePageBean = new HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean();
            chunnelHomePageBean.setDiscountPrice(contentBean.getAfterPrice());
            chunnelHomePageBean.setGoodsId(contentBean.getId());
            chunnelHomePageBean.setImage(contentBean.getIcon());
            chunnelHomePageBean.setPrice(contentBean.getPrice());
            chunnelHomePageBean.setTitle(contentBean.getTitle());
            chunnelHomePageBean.setGlink(contentBean.getLinks());
            if (!TextUtils.isEmpty(contentBean.getCouponAmount())) {
                chunnelHomePageBean.setCouponAmount(contentBean.getCouponAmount());
            }
            if (!TextUtils.isEmpty(contentBean.getCouponDiscount())) {
                chunnelHomePageBean.setCouponDiscount(contentBean.getCouponDiscount());
            }
            chunnelHomePageBean.setCouponId(contentBean.getCouponId());
            if (0 == contentBean.getIsReceive()) {
                chunnelHomePageBean.setCouponStatus(false);
            } else {
                chunnelHomePageBean.setCouponStatus(true);
            }
            list.add(chunnelHomePageBean);
        }
        return list;
    }


    @Override
    public void setGoodsData(LimitGoodsBean entity, String startTime, String endTime) {
        if (!Preconditions.isNullOrEmpty(entity.get_embedded()) && !Preconditions.isNullOrEmpty(entity.get_embedded().getContent())) {
            HomeFindBean.EmbeddedBean.ContentBean contentBean = new HomeFindBean.EmbeddedBean.ContentBean();
            contentBean.setId(10 + "");
            contentBean.setType(10);
            contentBean.setChunnelHomePage(getLimitGoodsData(entity.get_embedded().getContent(), entity));

            if (Preconditions.isNullOrEmpty(adapter.getData())) {
                return;
            }

            if (adapter.getData().size() > 4) {
                adapter.addData(4, contentBean);
            } else {
                adapter.addData(contentBean);
            }
        }
    }

    /**
     * 封装限时购
     *
     * @param content
     * @param entity
     * @return
     */
    private List<HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean> getLimitGoodsData(List<LimitGoodsBean.EmbeddedBeanXX.ContentBeanX> content, LimitGoodsBean entity) {
        List<HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean> list = new ArrayList<>();
        HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean chunnelHomePageBean = new HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean();
        chunnelHomePageBean.setStartTime(content.get(0).getLimitedStartTime());
        chunnelHomePageBean.setEndTime(content.get(0).getLimitedStopTime());
        if (!TextUtils.isEmpty(entity.getCurrentTime())) {
            chunnelHomePageBean.setServerTime(entity.getCurrentTime());
        } else {
            chunnelHomePageBean.setServerTime("");
        }
        List<HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean.GoodsLimitedBuysBean> goodsLimitedBuysBeans = new ArrayList<>();
        for (int i = 0; i < content.size(); i++) {
            HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean.GoodsLimitedBuysBean bean = new HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean.GoodsLimitedBuysBean();
            bean.setGoodsId(content.get(i).getId());
            bean.setImages(content.get(i).getIcon());
            if (content.get(i).getSkuInfos() != null && content.get(i).getSkuInfos().size() > 0) {
                bean.setPrice(content.get(i).getSkuInfos().get(0).getPrice());
                bean.setDiscountPrice(content.get(i).getSkuInfos().get(0).getDiscountPrice());
            }
            bean.set_links(content.get(i).get_links().getSelf().getHref());
            bean.setTitle(content.get(i).getTitle());
            bean.setOutline(content.get(i).getOutline());
            goodsLimitedBuysBeans.add(bean);
        }
        chunnelHomePageBean.setGoodsLimitedBuys(goodsLimitedBuysBeans);
        list.add(chunnelHomePageBean);
        return list;
    }

    @Override
    public void showError(String s, int type, int refreshFlag) {
        if (type == 0) {
            adapter.setEmptyView(errorView);
            homeMainRefresh.finishRefresh();
        }
        if (type == 1) {
            if (refreshFlag == AppConstants.ONLOADMORE) {
                adapter.loadMoreEnd();
            } else if (refreshFlag == AppConstants.ONREFRESH) {
                //获取新人专区数据
                mPresenter.getChunnelNewborn(0, 3);
                if (BaseUserUtils.getIsLogin(getActivity())) {
                    //获取限时购
                    mPresenter.initGoodsData(cityCode, "", "", 0, 10);
                }
            }
        }
    }

    public void setHomeFindBannerAutoPlay(boolean isAutoPlay) {
        if (adapter != null) {
            adapter.setBannerAutoPlay(isAutoPlay);
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        if (adapter != null) {
            adapter.setBannerAutoPlay(false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (adapter != null) {
            adapter.setBannerAutoPlay(true);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getInstance().unregister(ToLoginEvent.toLoginRxBusTag, toLoginRxBusObser);
    }
}
